import { Button, Col, Form, Input, InputNumber, Row, Select, Upload, message } from "antd";
import { useEffect, useState } from "react";
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const { Option } = Select;

// 产品分类数据
const categoryData = [
    { type: "treatment", name: "理疗项目" },
    { type: "medicine", name: "中药产品" },
    { type: "equipment", name: "养生器材" },
    { type: "drink", name: "保健饮品" },
    { type: "package", name: "定制套餐" }
];

// 图片上传前的校验
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传JPG/PNG格式的图片!');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
        return false;
    }
    return true;
};

export const UpdateProduct = (props) => {
    const { id } = props;
    console.log("产品id", id);
    
    // 产品数据 - 字段名与表单保持一致
    const [currentProduct, setCurrentProduct] = useState({
        id: 1,
        name: "推拿按摩",
        category: "treatment",
        price: 188.00,
        discountPrice: 168.00,
        specs: [
            { name: "30分钟" }, 
            { name: "60分钟" }
        ],
        description: "60分钟专业推拿，缓解肌肉疲劳，疏通经络，促进血液循环。适合长期办公族、颈椎腰椎不适人群。",
        serviceDuration: 60,
        servicePerson: "全部员工",
        effect: "缓解疲劳、疏通经络、促进血液循环",
        attention: "孕妇慎用，饭后1小时内不宜进行，皮肤有破损者不宜进行",
        mainImage: "https://picsum.photos/id/133/600/400",
        images: [
            "https://picsum.photos/id/134/600/400",
            "https://picsum.photos/id/135/600/400"
        ],
        status: "active",
        sort: 80,
        sales: 356,
        remarks: "需提前1天预约，周末及节假日价格上浮20%",
        serviceProcess: "1. 咨询评估 2. 准备工作 3. 专业推拿 4. 放松休息",
        serviceNote: "请提前15分钟到达，穿着宽松衣物",
        stock: 100,       // 库存，适用于实物产品
        unit: "次",       // 单位
        origin: "本地"    // 产地/来源
    });
  
    const [form] = Form.useForm();
    const [selectedCategory, setSelectedCategory] = useState("treatment");
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [mainImageFileList, setMainImageFileList] = useState([]);
    const [imageFileList, setImageFileList] = useState([]);

    // 初始化表单数据
    useEffect(() => {
        // 模拟从API获取产品数据
        // fetch(`/api/products/${id}`)
        //   .then(res => res.json())
        //   .then(data => {
        //     setCurrentProduct(data);
        //   });
        
        // 初始化主图
        const mainImageList = currentProduct.mainImage 
            ? [{
                uid: 'main-' + Date.now(),
                name: 'main-image.jpg',
                status: 'done',
                url: currentProduct.mainImage,
            }]
            : [];
            
        // 初始化图片列表
        const imgList = currentProduct.images.map((img, index) => ({
            uid: 'img-' + index + '-' + Date.now(),
            name: 'image-' + (index + 1) + '.jpg',
            status: 'done',
            url: img,
        }));
        
        setMainImageFileList(mainImageList);
        setImageFileList(imgList);
        
        // 设置表单初始值
        form.setFieldsValue({
            name: currentProduct.name,
            category: currentProduct.category,
            price: currentProduct.price,
            discountPrice: currentProduct.discountPrice,
            description: currentProduct.description,
            serviceDuration: currentProduct.serviceDuration,
            servicePerson: currentProduct.servicePerson,
            remarks: currentProduct.remarks,
            serviceProcess: currentProduct.serviceProcess,
            serviceNote: currentProduct.serviceNote,
            stock: currentProduct.stock,
            unit: currentProduct.unit,
            origin: currentProduct.origin
        });
        setSelectedCategory(currentProduct.category);
    }, [id, form, currentProduct]);

    // 处理分类变更
    const handleCategoryChange = (value) => {
        setSelectedCategory(value);
    };

    // 处理主图上传变化
    const handleMainImageChange = ({ file, fileList }) => {
        // 只保留一张主图
        if (fileList.length > 1) {
            fileList = [fileList[fileList.length - 1]];
        }
        setMainImageFileList(fileList);
        
        // 如果上传成功，更新currentProduct
        if (file.status === 'done') {
            setCurrentProduct(prev => ({
                ...prev,
                mainImage: file.response?.url || file.url
            }));
        }
    };

    // 处理图片列表上传变化
    const handleImageChange = ({ file, fileList }) => {
        setImageFileList(fileList);
        
        // 如果上传成功，更新currentProduct
        if (file.status === 'done') {
            const newImages = fileList
                .filter(f => f.status === 'done')
                .map(f => f.response?.url || f.url);
                
            setCurrentProduct(prev => ({
                ...prev,
                images: newImages
            }));
        }
    };

    // 查看图片预览
    const handlePreview = (file) => {
        setPreviewImage(file.url || file.thumbUrl);
        setPreviewVisible(true);
    };

    // 删除主图
    const handleMainImageRemove = () => {
        setMainImageFileList([]);
        setCurrentProduct(prev => ({
            ...prev,
            mainImage: ''
        }));
    };

    // 删除图片
    const handleImageRemove = (file) => {
        const newFileList = imageFileList.filter(f => f.uid !== file.uid);
        setImageFileList(newFileList);
        
        const newImages = newFileList
            .filter(f => f.status === 'done')
            .map(f => f.response?.url || f.url);
            
        setCurrentProduct(prev => ({
            ...prev,
            images: newImages
        }));
    };

    // 提交表单
    const handleSubmit = () => {
        form.validateFields()
            .then(values => {
                // 收集图片信息
                const formData = {
                    ...values,
                    id: currentProduct.id,
                    mainImage: mainImageFileList.length 
                        ? mainImageFileList[0].response?.url || mainImageFileList[0].url
                        : '',
                    images: imageFileList
                        .filter(f => f.status === 'done')
                        .map(f => f.response?.url || f.url)
                };
                
                console.log('表单提交数据:', formData);
                // 调用API提交数据
                // API.updateProduct(id, formData)
                //   .then(() => {
                //     message.success('产品信息更新成功');
                //     props.onSuccess(); // 通知父组件更新成功
                //   })
                //   .catch(error => {
                //     message.error('更新失败: ' + error.message);
                //   });
            })
            .catch(info => {
                console.log('表单验证失败:', info);
                message.error('请完善表单信息后再提交');
            });
    };

    // 主图上传组件
    const mainImageUploader = (
        <Upload
            name="mainImage"
            listType="picture-card"
            fileList={mainImageFileList}
            beforeUpload={beforeUpload}
            onChange={handleMainImageChange}
            onPreview={handlePreview}
            onRemove={handleMainImageRemove}
            maxCount={1}
        >
            {mainImageFileList.length >= 1 ? null : (
                <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传主图</div>
                </div>
            )}
        </Upload>
    );

    // 图片列表上传组件
    const imageUploader = (
        <Upload
            name="images"
            listType="picture-card"
            fileList={imageFileList}
            beforeUpload={beforeUpload}
            onChange={handleImageChange}
            onPreview={handlePreview}
            onRemove={handleImageRemove}
            maxCount={5} // 限制最多5张图片
        >
            {imageFileList.length >= 5 ? null : (
                <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
            )}
        </Upload>
    );

    return (
        <div className="modal-box" style={{ padding: '20px' }}>
            <Form
                form={form}
                layout="vertical"
                name="productForm"
            >
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="name"
                            label="产品名称"
                            rules={[{ required: true, message: '请输入产品名称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>

                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="category"
                            label="产品分类"
                            rules={[{ required: true, message: '请选择产品分类' }]}
                        >
                            <Select 
                                onChange={handleCategoryChange}
                                value={selectedCategory}
                            >
                                {categoryData.map(category => (
                                    <Option key={category.type} value={category.type}>
                                        {category.name}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>

                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="price"
                            label="原价 (元)"
                            rules={[{ required: true, message: '请输入原价' }]}
                        >
                            <InputNumber
                                min={0}
                                step={0.01}
                                style={{ width: '100%' }}
                                formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                            />
                        </Form.Item>
                    </Col>

                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="discountPrice"
                            label="优惠价 (元)"
                            rules={[{ required: true, message: '请输入优惠价' }]}
                        >
                            <InputNumber
                                min={0}
                                step={0.01}
                                style={{ width: '100%' }}
                                formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                parser={value => value.replace(/\¥\s?|(,*)/g, '')}
                            />
                        </Form.Item>
                    </Col>
                </Row>
    {/* 服务相关字段 - 所有产品类型都可编辑 */}
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={12}>
                        <Form.Item
                            name="serviceDuration"
                            label="服务时长(分钟)"
                            rules={[{ required: true, message: '请输入服务时长' }]}
                        >
                            <InputNumber min={0} style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                  
                </Row>
                                
                {/* 主图上传区域 - 所有产品类型都可编辑 */}
                <Form.Item
                    label="产品主图"
                    rules={[{ required: true, message: '请上传主图' }]}
                >
                    <div className="clearfix">
                        {mainImageUploader}
                    </div>
                    <p className="ant-upload-hint">
                        建议尺寸：600x400px，支持JPG/PNG格式，不超过2MB
                    </p>
                </Form.Item>

                {/* 图片列表上传区域 - 所有产品类型都可编辑 */}
                <Form.Item
                    label="产品图片"
                >
                    <div className="clearfix">
                        {imageUploader}
                    </div>
                    <p className="ant-upload-hint">
                        最多上传5张图片，支持JPG/PNG格式，每张不超过2MB
                    </p>
                </Form.Item>

                <Form.Item
                    name="description"
                    label="产品描述"
                    rules={[{ required: true, message: '请输入产品描述' }]}
                >
                    <TextArea rows={4} placeholder="请详细描述产品特点、功效等信息" />
                </Form.Item>

            
              

                {/* <Form.Item
                    name="serviceProcess"
                    label="服务流程"
                    rules={[{ required: true, message: '请输入服务流程' }]}
                >
                    <TextArea rows={4} placeholder="请描述服务的详细流程步骤" />
                </Form.Item> */}

                <Form.Item
                    name="serviceNote"
                    label="注意事项"
                    rules={[{ required: true, message: '请输入注意事项' }]}
                >
                    <TextArea rows={3} placeholder="请填写使用或服务中的注意事项" />
                </Form.Item>

                <Form.Item
                    name="remarks"
                    label="备注信息"
                >
                    <TextArea rows={3} placeholder="其他需要说明的信息" />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" onClick={handleSubmit} style={{ marginRight: 16 }}>
                        保存修改
                    </Button>
                   
                </Form.Item>
            </Form>

            {/* 图片预览模态框 */}
            {previewVisible && (
                <div 
                    style={{ 
                        position: 'fixed',
                        top: 0,
                        bottom: 0,
                        left: 0,
                        right: 0,
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 9999,
                        cursor: 'zoom-out'
                    }}
                    onClick={() => setPreviewVisible(false)}
                >
                    <img 
                        src={previewImage} 
                        style={{ 
                            maxWidth: '90%',
                            maxHeight: '90%',
                            objectFit: 'contain'
                        }} 
                        alt="产品图片预览"
                    />
                </div>
            )}
        </div>
    );
};
